package com.jesse.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.view.MotionEvent;
import android.widget.Button;

import com.jesse.dao.ButtonDao;
import com.jesse.main.R;
import com.jesse.observer.DefaultEvent;
import com.jesse.observer.ObserverBus;
import com.jesse.util.AppUtil;
import com.jesse.util.ViewUtil;

public class ActivityUtil {

	private float xDown;
	private float xUp;
	private boolean isOverFIXED;
	private final int FIXED = (int) (ViewUtil.getScreenWidth() * 0.2);
	public boolean gestrue = true;
	public boolean showNetErrorPopup = true;
	public boolean showWiFiErrorPopup = true;
	public boolean isCheckWifiState = false;
	private ButtonDao cancleUserWIfiButtonDao = null;
	private OnNetStatusChange netStatusChange;
	
	protected ConnectivityManager connectivityManager;
	
	protected void onResume(Context context) {
		//检测网络状态
		checkNetStateAvailable(context);
		//注册网络变化监听，注意可以在子类中的resume方法中去实现网络状态监听
		registerReceiver(context);
		checkGuider();
	}
	
	/**
	 * Hook
	 */
	protected void checkGuider() {
		
	}
	
	//手勢开关
	public boolean isGestrue() {
		return gestrue;
	}
	
	public void setGestrue(boolean gestrue) {
		this.gestrue = gestrue;
	}
	
	public void setOnNetStatusListener(OnNetStatusChange statusChange) {
		this.netStatusChange = statusChange;
	}
	
	//是否网络未连接时弹出对话框
	public void notShowNetErrorPopup() {
		showNetErrorPopup = false;
	}
	
	public void notShowWiFiErrorPopup() {
		showWiFiErrorPopup = false;
	}
	
	//检测WiFi状态
	public boolean checkWiFiState(Context context) {
		isCheckWifiState = true;
		return checkWiFiAvailable(context);
	}

	//检测WiFi状态,并设置取消键回掉
	public boolean checkWiFiState(Context context, ButtonDao buttonDao) {
		isCheckWifiState = true;
		cancleUserWIfiButtonDao = buttonDao;
		return checkWiFiAvailable(context);
	}

	protected boolean dispatchTouchEvent(Context context, MotionEvent event) {
		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			xDown = event.getX();
			break;
		case MotionEvent.ACTION_UP:
			xDown = 0;
			xUp = 0;
			break;
		case MotionEvent.ACTION_MOVE:
			xUp = event.getX();
			isOverFIXED = xUp - xDown > FIXED ? true : false;
			if (isOverFIXED && gestrue && xDown < ViewUtil.getScreenWidth() / 8) {
				return true;
			}
			break;
		}
		return false;
	}
	
	/**
	 * 当前网络状态广播监听
	 * @param context
	 */
	public void registerReceiver(Context context) {
		IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(mReceiver, mFilter);
	}
	
	public void unregisterReceiver(Context context) {
		context.unregisterReceiver(mReceiver);	
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
	 	
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            try {
	            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
	            	checkNetStateChangeAvailable(context);
	            	if (isCheckWifiState) {
	            		checkWiFiAvailable(context);
	            	}
	            }
            } catch (java.lang.RuntimeException e){
            	
            }
        }
    };
    
    /**
     * 检测网络当前状态
     * @param context
     * @return
     */
    public boolean checkNetStateAvailable(Context context) {
    	connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	NetworkInfo info = connectivityManager.getActiveNetworkInfo(); 
       
        if(info == null || !info.isAvailable()) {
        	netError(context);
        	return false;
        } else if(info != null && info.isConnected()){
        	netNormal();
           return true;
        }
    	return false;
    }
    
    /**
     * 网络变化状态
     * @param context
     * @return
     */
    public boolean checkNetStateChangeAvailable(Context context) {
    	connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	NetworkInfo info = connectivityManager.getActiveNetworkInfo(); 
        if(info == null || (!info.isAvailable() && AppUtil.netStateOk)) {
        	netError(context);
        	return false;
        } else if(info != null && info.isConnected() && !AppUtil.netStateOk){
    	    netRecover();
           return true;
        }
    	return false;
    }
    
    /**
     * 检测wifi是否可用
     * @param context
     * @return
     */
    public boolean checkWiFiAvailable(Context context) {
    	connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    	NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
    	if (wifiInfo != null && wifiInfo.isConnected()) {
    		wifiRecover();
    		return true;
    	} else {
    		wifiError(context);
    		return false;
    	}
    }
    
    private synchronized void netError(Context context) {
    	ViewUtil.Debug("网络不可用");
		AppUtil.netStateOk = false;
    	ObserverBus.getInstance().updateEvent(DefaultEvent.NETSTATE, false);
    	popupNetSetting(context);
    	if (netStatusChange != null) {
    		netStatusChange.netError();
    	}
    }
    
    private synchronized void netNormal() {
    	ViewUtil.Debug("网络可用");
		AppUtil.netStateOk = true;
    	ViewUtil.closePopup();
    }
    
    private synchronized void netRecover() {
    	netNormal();
    	ObserverBus.getInstance().updateEvent(DefaultEvent.NETSTATE, true);
    	if (netStatusChange != null) {
    		netStatusChange.netRecover();
    	}
    }
    
    private synchronized void wifiError(Context context) {
    	ViewUtil.Debug("wifi不可用");
		AppUtil.wifiStateOk = false;
    	ObserverBus.getInstance().updateEvent(DefaultEvent.WIFISTATE, false);
    	if (AppUtil.netStateOk) {
    		//网络不可用时，首先提示网络状态
    		popupWiFiSetting(context);
    	}
    }
    
    private synchronized void wifiRecover() {
    	ViewUtil.Debug("wifi可用");
		AppUtil.wifiStateOk = true;
    	ObserverBus.getInstance().updateEvent(DefaultEvent.WIFISTATE, true);
    	ViewUtil.closePopup();
    }
    
    /**
     * 网络问题提示框
     * @param context
     */
    private void popupNetSetting(final Context context) {
    	if (!showNetErrorPopup) return;
    	
    	ViewUtil.popupWithTwoButton(context, context.getString(R.string.netError), context.getString(R.string.alert), context.getString(R.string.netSetting), 
			new ButtonDao() {
				
				@Override
				public void onClick() {
					Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
					context.startActivity(intent);
				}
				
			}, context.getString(R.string.cancel), new ButtonDao() {
				
				@Override
				public void onClick() {
				}
		});
    }
    
    /**
     * wifi问题提示框
     * @param context
     */
    private void popupWiFiSetting(final Context context) {
    	if (!showWiFiErrorPopup) return;
    	
    	ViewUtil.popupWithTwoButton(context, context.getString(R.string.wifiErrorContext), context.getString(R.string.wifiError), context.getString(R.string.wifiSetting), 
			new ButtonDao() {
				
				@Override
				public void onClick() {
					Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
					context.startActivity(intent);
				}
				
			}, context.getString(R.string.wifiCancel), new ButtonDao() {
				
				@Override
				public void onClick() {
					if (cancleUserWIfiButtonDao != null) {
						cancleUserWIfiButtonDao.onClick();
					}
				}
		});
    }
    
    protected void finish(Context context) {
		ViewUtil.endWaiting();
		ViewUtil.closePopup();
	}
	
    public void onDestroy(Context context) {
    	try {
    		if (mReceiver != null) {
    			context.unregisterReceiver(mReceiver);
    		}
    	} catch (IllegalArgumentException e) {
    		if (AppUtil.DEBUG) {
    			e.printStackTrace();
    		}
    	}
    	finish(context);
    	mReceiver = null;
    	netStatusChange = null;
        ViewUtil.hideKeyBoard(context);
    }
    

	public interface OnNetStatusChange {
		void netError();
		void netRecover();
	}
}
